package goodenglish.domain.service.analysis;

import goodenglish.domain.model.subt.SubtSentence;
import goodenglish.infrastructure.Config;
import goodenglish.infrastructure.DateUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 从文本文件中导入句子
 * 
 * @author hp
 * 
 */
public class TxtAnalyzer extends ImportAnalyzer {
	public TxtAnalyzer(final File file) {
		super(file);
	}

	/**
	 * 从字幕串里分析出句子
	 * 
	 * @param subtStr
	 * @param subt
	 */
	@Override
	public List<SubtSentence> analysisSentens() {
		List<SubtSentence> sentences = new ArrayList<SubtSentence>();
		String[] sentenceStrAll = subtStr.split(Config.LINE_SPLITER);
		for (final String sentenceStr : sentenceStrAll) {
			SubtSentence sentence = new SubtSentence();
			this.setChEnStr(sentence, sentenceStr);
			sentences.add(sentence);
		}
		// 设置句子的开始结束时间
		for (int i = 0; i < sentences.size(); i++) {
			SubtSentence sentence = sentences.get(i);
			if (i == sentences.size() - 1) {
				sentence.setEtime(Integer.MAX_VALUE);
			} else {
				sentence.setEtime(sentences.get(i + 1).getStime());
				sentence.setEtimeStr(sentences.get(i + 1).getStimeStr());
			}

		}
		return sentences;
	}

	private void setChEnStr(SubtSentence subtSentence, final String sentenceStr) {
		subtSentence.setStimeStr(sentenceStr.substring(0, 8));
		int stime = DateUtil.getSecondsFromTimeStr(subtSentence.getStimeStr());
		subtSentence.setStime(stime);

		/**
		 * 查找中文结束的地方
		 */
		int indexChEnd = -1;
		for (int i = sentenceStr.length() - 1; i >= 0; i--) {
			if (sentenceStr.charAt(i) >= 0x4E00 && sentenceStr.charAt(i) <= 0x9FA5) {
				indexChEnd = i;
				break;
			}
		}
		if (-1 == indexChEnd) {
			subtSentence.setEnStr(sentenceStr.substring(8));
			subtSentence.setChStr("");
			return;
		}
		/**
		 * 查找英文开始的地方
		 */
		int indexEnStart = -1;
		for (int j = indexChEnd; j < sentenceStr.length(); j++) {
			char c = sentenceStr.charAt(j);
			if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
				indexEnStart = j;
				break;
			}
		}
		if (-1 != indexEnStart) {
			subtSentence.setChStr(sentenceStr.substring(8, indexEnStart).trim());
			subtSentence.setEnStr(sentenceStr.substring(indexEnStart).trim());
		} else {
			// 如果只有中文
			subtSentence.setChStr(sentenceStr.substring(8).trim());
		}

	}
}
